package com.hanxu.mallproduct.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hanxu.common.constant.ProductConstant;
import com.hanxu.common.to.SkuReductionTo;
import com.hanxu.common.to.SpuBoundTo;
import com.hanxu.common.to.es.SkuEsModel;
import com.hanxu.common.utils.R;
import com.hanxu.mallproduct.dao.*;
import com.hanxu.mallproduct.entity.*;
import com.hanxu.mallproduct.feign.CouponFeignService;
import com.hanxu.mallproduct.feign.SearchFeignService;
import com.hanxu.mallproduct.feign.WareFeignService;
import com.hanxu.mallproduct.service.SpuInfoDescService;
import com.hanxu.mallproduct.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hanxu.common.utils.PageUtils;
import com.hanxu.common.utils.Query;

import com.hanxu.mallproduct.service.SpuInfoService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescDao spuInfoDescDao;
    @Autowired
    SpuImagesDao spuImagesDao;
    @Autowired
    AttrDao attrDao;
    @Autowired
    ProductAttrValueDao productAttrValueDao;
    @Autowired
    SkuInfoDao skuInfoDao;
    @Autowired
    SkuImagesDao skuImagesDao;
    @Autowired
    SkuSaleAttrValueDao skuSaleAttrValueDao;
    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandDao brandDao;
    @Autowired
    CategoryDao categoryDao;

    @Autowired
    WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        // 保存spu的描述图片 pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescDao.insert(spuInfoDescEntity);
        // 保存spu的图片集 pms_spu_images
        List<String> images = spuSaveVo.getImages();
        if (images != null && !images.isEmpty()) {
            for (String image : images) {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(image);
                spuImagesDao.insert(spuImagesEntity);
            }
        }

        // 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        if (baseAttrs != null && !baseAttrs.isEmpty()) {
            for (BaseAttrs baseAttr : baseAttrs) {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                AttrEntity attrEntity = attrDao.selectById(productAttrValueEntity.getAttrId());
                productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueDao.insert(productAttrValueEntity);
            }
        }

        // 保存spu的积分信息：mall_sms ->(sms_spu_bounds)
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        couponFeignService.saveSpuBounds(spuBoundTo);

        // 保存当前spu对应的所有sku信息
        // 保存sku的基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        if (skus != null && skus.size() > 0) {
            for (Skus sku : skus) {
                String defaultImg = "";// 默认图像的名称
                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoDao.insert(skuInfoEntity);

                // 保存sku的图片集 pms_spu_images
                Long skuId = skuInfoEntity.getSkuId();
                for (Images image : sku.getImages()) {
                    if (image.getImgUrl() != null) {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        skuImagesEntity.setSkuId(skuId);
                        skuImagesEntity.setImgUrl(image.getImgUrl());
                        skuImagesEntity.setDefaultImg(image.getDefaultImg());
                        skuImagesDao.insert(skuImagesEntity);
                    }
                }

                // 保存sku的销售属性信息 pms_sku_sale_attr_value
                List<Attr> attrs = sku.getAttr();
                for (Attr attr : attrs) {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    skuSaleAttrValueDao.insert(skuSaleAttrValueEntity);
                }

                // 保存sku的优惠、满减等信息：
                // mall_sms ->(sms_sku_ladder、sms_sku_full_reduction、sms_member_price)
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal(0)) > 0) {
                    couponFeignService.saveSkuReduction(skuReductionTo);

                }
            }
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) throws UnsupportedEncodingException {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasText(key)) {
            String tmpKey = URLDecoder.decode(key, StandardCharsets.UTF_8);
            wrapper.and((queryWrapper) -> {
                queryWrapper.eq("id", tmpKey).or().like("spu_name", tmpKey);
            });
        }

        String status = (String) params.get("status");
        if (StringUtils.hasText(status)) {
            wrapper.and((w) -> {
                w.eq("publish_status", status);
            });
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.hasText(brandId)) {
            wrapper.and((w) -> {
                w.eq("brand_id", brandId);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasText(catelogId)) {
            wrapper.and((w) -> {
                w.eq("catalog_id", catelogId);
            });
        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);


    }
    @Transactional
    @Override
    public void up(Long spuId) throws JsonProcessingException {
        // 查询sku当前的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueDao.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> searchAttrIds = new ArrayList<>();
        for (ProductAttrValueEntity baseAttr : baseAttrs) {
            AttrEntity attrEntity = attrDao.selectOne(new QueryWrapper<AttrEntity>().eq("attr_id", baseAttr.getAttrId()).and((w) -> {
                w.eq("search_type", 1);
            }));
            searchAttrIds.add(attrEntity.getAttrId());
        }
        Set<Long> set = new HashSet<>(searchAttrIds);
        List<SkuEsModel.Attrs> attrsList = new ArrayList<>();
        for (ProductAttrValueEntity baseAttr : baseAttrs) {
            if (set.contains(baseAttr.getAttrId())) {
                SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
                BeanUtils.copyProperties(baseAttr, attrs);
                attrsList.add(attrs);
            }
        }

        List<SkuEsModel> skuEsModels = new ArrayList<>();
        // 组装数据
        SkuEsModel skuEsModel = new SkuEsModel();
        // 查出当前spuId对应的所有sku信息、品牌的名字
        List<SkuInfoEntity> skus = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIdList = new ArrayList<>();
        for (SkuInfoEntity skuInfoEntity : skus) {
            skuIdList.add(skuInfoEntity.getSkuId());
        }

        // 发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = new HashMap<>();
        try {
            R hasStock = wareFeignService.getSkusHasStock(skuIdList);
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, Object> jsonMap = objectMapper.readValue(objectMapper.writeValueAsString(hasStock), new TypeReference<Map<String, Object>>() {
            });
            List<SkuHasStockVo> skuHasStockVos = objectMapper.readValue(objectMapper.writeValueAsString(jsonMap.get("data")), new TypeReference<List<SkuHasStockVo>>() {
            });
            for (SkuHasStockVo skuHasStockVo : skuHasStockVos) {
                stockMap.put(skuHasStockVo.getSkuId(), skuHasStockVo.getHasStock());
            }
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);
        }

        // 封装每个sku的信息
        List<SkuEsModel> esModels = new ArrayList<>();
        for (SkuInfoEntity skuInfoEntity : skus) {
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, esModel);
            esModel.setSkuPrice(skuInfoEntity.getPrice());
            esModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            // 库存系统是否有库存
            esModel.setSkuId(skuInfoEntity.getSkuId());
            esModel.setHasStock(stockMap.get(skuInfoEntity.getSkuId()));

            //TODO 热度评分
            esModel.setHotScore(0L);
            // 查询品牌和分类的名字信息
            BrandEntity brand = brandDao.selectById(skuInfoEntity.getBrandId());
            if (brand != null) {
                esModel.setBrandName(brand.getName());
                esModel.setBrandImg(brand.getLogo());
            } else {
                log.error("brand：{}，不存在", skuInfoEntity.getBrandId());
            }

            CategoryEntity category = categoryDao.selectById(skuInfoEntity.getCatalogId());
            esModel.setCategoryName(category.getName());
            // 设置检索属性
            esModel.setAttrs(attrsList);
            esModels.add(esModel);
        }
        // 将数据发送给es进行保存：mall-search
        R r = searchFeignService.productStatusUp(esModels);
        if (r.getCode() == 0) {
            // 远程调用成功
            // 修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // 远程调用失败
            //TODO 重复调用？接口幂等性？重试机制？


        }

    }


}